#include "video.h"
#include "ui_video.h"
#include <QFileDialog>
#include <QImage>
#include <QImageReader>
#include "globalval.h"
Video::Video(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Video)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    connect(ui->pushButtonGetVideo, &QPushButton::clicked, this, &Video::sendVideoRequest);
    connect(udpSocket, &QUdpSocket::readyRead, this, &Video::processPendingDatagrams);
    connect(ui->pushButtonPhoto, &QPushButton::clicked, this, &Video::saveImage);
}

Video::~Video()
{
    delete ui;
}
// 发送获取视频的请求
void Video::sendVideoRequest()
{
    QString text("get_stream");
    QByteArray array = text.toUtf8();
    QHostAddress serverAddress(GlobalVal::serverIp);
    quint16 serverPort = 8888;
    udpSocket->writeDatagram(array, serverAddress, serverPort);
}
// 获取视频帧显示到页面上
void Video::processPendingDatagrams()
{
    QByteArray datagram;
    while(udpSocket->hasPendingDatagrams())
    {
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size());
        QImage image;
        if (image.loadFromData(datagram)) {

            ui->labelVideo->setPixmap(QPixmap::fromImage(image));
            ui->labelVideo->resize(image.size());
        }
        else {
            qDebug() << "Failed to load image from data";
        }
    }
}
// 保存图片，使用自带的函数
void Video::saveImage() {
    QString fileName = QFileDialog::getSaveFileName(this, "Save Image", "", "Images (*.png *.xpm *.jpg)");
    if (!fileName.isEmpty()) {
        QPixmap pixmap = ui->labelVideo->grab();
        pixmap.save(fileName);
    }
}
